<template>
  <div class="info-container">
    <el-card>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form label-width="200px">
        <el-form-item label="品牌：">{{ info.brand || '' }}</el-form-item>
        <el-form-item label="车型：">{{ info.model || '' }}</el-form-item>
        <el-form-item label="车牌：">{{ info.carNumber || '' }}</el-form-item>
        <el-form-item label="车身颜色：">{{ info.colour || '' }}</el-form-item>
        <el-form-item label="价格：">
          <span class="text-red2">￥{{ info.price || '' }}</span> <span class="text-light">元/日</span>
        </el-form-item>
        <el-form-item label="服务包：">
          <el-checkbox-group v-model="formData.serverIds">
            <el-checkbox v-for="(item,i) of info.carServerList||[]" :key="i" :label="item.id">
              {{ item.name }}（￥{{ item.price || 0 }}元）
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="租赁天数：">
          <el-input-number v-model="formData.days" :min="1" :max="99999"></el-input-number>
        </el-form-item>
        <el-form-item label="租金：">
          <span class="text-red2">￥{{ totalAmount || '0.00' }}</span> <span class="text-light">元</span>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
              type="textarea"
              v-model="formData.memo" placeholder="备注信息" maxlength="200"
              show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button @click="onCreateOrder" type="danger">
            立即租赁
          </el-button>
        </el-form-item>
      </el-form>

    </el-card>

    <el-card class="m_y10" v-if="info.intro&&info.intro.length&&info.images&&info.images.length">
      <div class="p_y20">{{ info.intro }}</div>
      <div class="row-align-center flex-wrap images">
        <el-image class="image" alt="" :src="item" v-for="item of info.images||[]" :key="item"></el-image>
      </div>
    </el-card>

  </div>
</template>

<script>
import {computed, defineComponent, reactive, ref} from "vue"
import {useRoute, useRouter} from "vue-router";
import Goods from "../api/modules/Goods";
import {bcAdd, bcMul} from "../utils/helpers";
import Toast from "../utils/Toast";
import Orders from "../api/modules/Orders";
import {useStore} from "vuex";
import {useUserLogin} from "../hooks/user/useUserLogin";
import Events from "../events/Events";

export default defineComponent({
  name: "GoodInfo",
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const loginHandle = useUserLogin();
    const info = ref({})
    const formData = reactive({
      serverIds: [],
      days: "",
      memo: "", // 备注
    })
    getInfo(route.query.id)

    // 租金
    const totalAmount = computed(() => {
      const {serverIds, days} = formData;
      const {carServerList, price} = info.value;
      let total = bcMul(price || '0', days || '0');
      if (serverIds.length) {
        (carServerList || []).forEach(item => {
          if (serverIds.indexOf(item.id) > -1) {
            total = bcAdd(total, item.price);

          }
        })
      }
      return total;
    });

    async function getInfo(goodId) {
      try {
        const {data} = await Goods.info(goodId);
        if (data) {
          try {
            data.images = JSON.parse(data.images)
          } catch (e) {
            data.images = [];
          }
          info.value = data;
        }
        console.log(data)
      } catch (e) {

      }
    }

    async function onCreateOrder() {
      const userId = store.state.user.userInfo.id;
      if (!userId) { // 未登录
        loginHandle.removeUserInfo(false); // 当管理员登录时自动退出（仅用户登录可购买）
        window.emitter.emit(Events.showLoginModal); // 触发显示登录弹框事件
        return;
      }
      const {serverIds, days, memo} = formData;
      if (serverIds.length === 0) {
        Toast.warning('请至少选择一个服务包');
        return;
      }
      try {
        const {message} = await Orders.create({
          days,
          memo,
          serverIds: JSON.stringify(serverIds),
          carId: info.value.id,
          userId
        });
        Toast.success(message);
        window.emitter.emit(Events.refreshUserInfo); // 刷新用户信息
        router.push('/'); // 返回首页
      } catch (e) {
        Toast.warning(e.message);
      }
    }

    return {
      info,
      formData,
      totalAmount,
      onCreateOrder,
    }
  },
})
</script>

<style lang="scss" scoped>
.info-container {
  .left-box {
    width: 400px;
  }

  .images {
    .image {
      max-width: 100%;
    }
  }
}

</style>
